package com.qdu.reducer;

import com.qdu.bean.RentCarBean;
import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.*;

public class Top5CountByHourReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
    Map<Integer, Integer> map = new HashMap<>();
    IntWritable keyOut = new IntWritable();
    IntWritable valueOut = new IntWritable();

    @Override
    protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

        int count = 0;
        for (IntWritable i : values) {
            count += i.get();
        }

        valueOut.set(count);
        map.put(Integer.parseInt(key.toString()), valueOut.get());
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {

        LinkedList<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        for (int i = 0; i < 10; i++) {
            keyOut.set(list.get(i).getKey());
            valueOut.set(list.get(i).getValue());
            context.write(keyOut, valueOut);
        }

        //    @Override
//    protected void cleanup(Context context) throws IOException, InterruptedException {
//        LinkedList<Map.Entry<Integer,Integer>> list=new LinkedList<>(map.entrySet());
//        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
//            @Override
//            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
//                return 0;
//            }
//        });
//
//        for (int i=0;i<10;i++){
//            keyOut.set(list.get(i).getKey());
//            valueOut.set(list.get(i).getValue());
//            context.write(keyOut,valueOut);
//        }
//    }
    }
}
